import 'package:flutter/material.dart';

import './contacts_data.dart' show ContactData,Contacts;

class ContactPage extends StatefulWidget{

  @override
  _contactPage createState() => _contactPage();
}
class _contactPage extends State<ContactPage>{
  Map obj = {};
  int num = 0;
  int bgcolor = 0x00aaaaaa;
  ScrollController _scrollController = new ScrollController();
  final List<Contacts> dataArr = [];
  final ContactData contacts = ContactData.mock();
  void initState(){
    dataArr..addAll(contacts.contacts)..addAll(contacts.contacts)..addAll(contacts.contacts);
    dataArr.sort((Contacts a,Contacts b)=> a.nameIndex.compareTo(b.nameIndex));
    for(int i=0;i<dataArr.length;i++){
      if(i==0){
        obj[dataArr[0].nameIndex] = num;
      }else if(dataArr[i].nameIndex != dataArr[i-1].nameIndex){
//        print(dataArr[i].nameIndex);
      num+=30;
      }else{
        num+=60;
      }
      obj[dataArr[i].nameIndex] = num;
    }
  }
  List quickBar=const[
    "↑", "☆",
    "A", "B", "C", "D", "E", "F", "G",
    "H", "I", "J", "K", "L", "M", "N",
    "O", "P", "Q", "R", "S", "T", "U",
    "V", "W", "X", "Y", "Z"
  ];
  String word = '';
  int wordIndex = 0;
  void _getQuickBarIndex(detail){
    RenderBox _box = context.findRenderObject();
    double _globDy = _box.globalToLocal(detail.globalPosition).dy;
    double _containerHeight = _globalkey.currentContext.size.height;
    int _wordIndex = (_globDy / _containerHeight * quickBar.length).floor().clamp(0,quickBar.length-1);
    setState((){
      word = quickBar[_wordIndex];
      wordIndex=_wordIndex;
    });
  }

  GlobalKey _globalkey = new GlobalKey();
  @override
  Widget build(BuildContext context) {
    List<Widget> _quickBarItem =[];
    quickBar.forEach((w){
      _quickBarItem.add(
          new Expanded(
            child: new Text(w) ,
          )
      );
    });
    // TODO: implement build
    return new Stack(
      children: <Widget>[
        new ListView.builder(
//        scrollDirection:Axis.vertical,
//        shrinkWrap: true,
        itemBuilder: (BuildContext context,int index){
          return new _contactItem(contacts:dataArr,index:index);
        },
          controller: _scrollController,
        itemCount: dataArr.length,
        ),
        new Positioned(
          right:0,
          top:0,
          bottom:0,
          child: new Container(
            key:_globalkey,
            width:30,
            color:Color(bgcolor),
            child:new GestureDetector(
              child:new Column(
                  children:_quickBarItem
              ),
              onVerticalDragDown:(DragDownDetails detail){
                print(obj);
                _getQuickBarIndex(detail);
                String _w=quickBar[wordIndex];
                print(obj[_w]);
                double aaa = wordIndex*60.toDouble();
                _scrollController.animateTo(
                    aaa,
                    duration: Duration(milliseconds: 200),
                    curve: Curves.easeIn
                );
                setState((){
                  bgcolor = 0x99aaaaaa;
                });
              },
              onVerticalDragStart: (DragStartDetails detail){

                print(detail);
              },
              onVerticalDragEnd: (DragEndDetails detail){
                print(detail);
                setState((){
                  bgcolor = 0x00aaaaaa;
                  word = '';

                });
              },
              onVerticalDragUpdate:(DragUpdateDetails detail){
                print(detail.globalPosition.dy);
                _getQuickBarIndex(detail);
              },
              onVerticalDragCancel: (){
                setState((){
                  bgcolor = 0x00aaaaaa;
                  word = '';
                });
              }
            )
          ),
        ),
        new Center(
            child:word==''?new Text(''):new Container(
                alignment: Alignment.center,
                width:100.0,
                height:100.0,
                child: new Text(
                    word,
                    style:TextStyle(
                      color: Colors.white,
                      fontSize:80.0,
                    )
                ),
                decoration:BoxDecoration(
                    color:Colors.black54,
                    borderRadius: BorderRadius.all(
                        Radius.circular(12.0)
                    )
                )
            )
        )
      ]
    );
  }
}

class _contactItem extends StatelessWidget{
  const _contactItem({
    Key key,
    this.contacts,
    this.index
  });
  final List<Contacts> contacts;
  final int index;

  @override
  Widget build(BuildContext context) {
    Widget _item;
    Contacts contact = contacts[index];
    Widget _nameIndexItem = new Container(
        padding:const EdgeInsets.symmetric(
          horizontal: 10.0
        ),
        height:30,
        child:new Text(contact.nameIndex),
        alignment:Alignment.centerLeft,
        decoration:BoxDecoration(
            color:const Color(0xffeeeeee),
            border:Border(
                bottom:BorderSide(
                    width:1,
                    color:const Color(0xffdddddd)
                ),
                top:BorderSide(
                    width:1,
                    color:const Color(0xffdddddd)
                )
            )
        )
    );

    _item = new Container();
    bool _isIndex=true;
    if(index>0){
      _isIndex= contact.nameIndex!=contacts[index-1].nameIndex;
    }
    if(index==0){
      _item= _nameIndexItem;
    }else if(contact.nameIndex!=contacts[index-1].nameIndex){
      _item= _nameIndexItem;
    }
    return new Column(
      children:<Widget>[
        _item,
        new Row(
          children:<Widget>[
            _userAvatar(avatar:contact.avatar),
            _userTitle(title:contact.name,isIndex:_isIndex)
          ]
        )
      ]
    );
  }
}

class _userAvatar extends StatelessWidget{
  const _userAvatar({this.avatar});
  final String avatar;
  @override
  Widget build(BuildContext context) {
    Widget ImageItem;
    if(avatar.indexOf('http')!=-1){
      ImageItem = new Image.network(
        avatar,
        width: 40,
        height:40,
      );
    }else{
      ImageItem = new Image.asset(
        avatar,
        width: 40,
        height:40,
      );
    }
    // TODO: implement build
    return new Container(
      padding:const EdgeInsets.symmetric(
        vertical:10.0,
        horizontal:15.0
      ),
      height:60.0,
      child:ImageItem
    );
  }
}

class _userTitle extends StatelessWidget{
  const _userTitle({
    this.title,
    this.isIndex
});
  final bool isIndex;

  final String title;
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Expanded(
        child: new Container(
            height:60.0,
            padding:const EdgeInsets.symmetric(
              vertical:10.0,
            ),
            alignment: Alignment.centerLeft,
            child:new Text(title),
            decoration:BoxDecoration(
                border:Border(
                    top: BorderSide(
                        width:1,
                        color:isIndex?Colors.transparent:new Color(0xffdddddd)
                    )
                )
            )
        )
    );
  }
}